package msc.dodo.wtb.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import msc.dodo.wtb.api.ApiInfoList;
import msc.dodo.wtb.response.RespDto;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;


/**
 * 发送http请求工具类
 */
@Slf4j
public class HttpUtil {

    /**
     * 机器人唯一标识
     */
    private static final String CLIENTID = "28137466";
    /**
     * 机器人鉴权Token
     */
    private static final String TOKEN = "MjgxMzc0NjY.77-977-90ro.hyipSoDjCwsgop4J2ohrYGBz0Zaj4oYROFq7rHwDAdM";
    /**
     * dodo接口地址
     */
    private static final String URL = "https://botopen.imdodo.com";

    /**
     * 发送数据格式为json的请求
     * @param body 发送内容
     * @param apiInfoList 配置信息
     * @return
     */
    public static RespDto sendJsonByHTTP(JSONObject body, ApiInfoList apiInfoList){
        try{
            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.valueOf(apiInfoList.getMediaType()));
            httpHeaders.set("Authorization","Bot "+CLIENTID+"."+TOKEN);
            HttpEntity httpEntity = new HttpEntity(body,httpHeaders);
            ResponseEntity<RespDto> response = restTemplate.exchange(URL+ apiInfoList.getPort(), apiInfoList.getHttpMethod(), httpEntity, RespDto.class);
            return response.getBody();
        }catch(Exception e){
            e.printStackTrace();
            return new RespDto().failure("接口["+ apiInfoList.getPort()+"]调用发生异常");
        }
    }

    /**
     * 发送数据格式为byte的请求
     * @param context 发送内容
     * @param apiInfoList 配置信息
     * @return
     */
    public static RespDto sendByteByHTTP(byte[] context, ApiInfoList apiInfoList){
        try{
            RestTemplate restTemplate = new RestTemplate();
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();

            param.add("file", new ByteArrayResource(context) {
                @Override
                public String getFilename() {
                    return "msc.png";
                }
            });

            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setContentType(MediaType.valueOf(apiInfoList.getMediaType()));
            httpHeaders.set("Authorization","Bot "+CLIENTID+"."+TOKEN);
            httpHeaders.setContentLength(context.length);

            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(param, httpHeaders);
            ResponseEntity<RespDto> response = restTemplate.postForEntity(URL+ apiInfoList.getPort(), requestEntity, RespDto.class);
            return response.getBody();
        }catch(Exception e){
            e.printStackTrace();
            return new RespDto().failure("接口["+ apiInfoList.getPort()+"]调用发生异常");
        }
    }


}
